<script setup lang="ts">
import type { EmployeeVO } from '#/api/company/audience/model';

import { computed, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { cloneDeep } from '@vben/utils';

import { useVbenForm } from '#/adapter/form';
import { personalFavoriteAddMember } from '#/api/company/favorite/personal';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';

const props = withDefaults(defineProps<Props>(), {
  btnText: undefined,
  idKey: 'id',
  addByCheckCompanyApi: () => undefined,
  addBySearchApi: () => undefined,
});

const emit = defineEmits<{ reload: [] }>();

interface Props {
  btnText?: string;
  idKey?: string;
  /**
   * 按勾选加入收藏夹API
   */
  addByCheckCompanyApi?: any;
  /**
   * 按条件搜索加入收藏夹API
   */
  addBySearchApi?: any;
}

const checkedCount = ref(0);
const confirmText = computed(() => {
  return (
    props.btnText ??
    (checkedCount.value > 0
      ? `确认加入${checkedCount.value}条数据`
      : `确认加入`)
  );
});
const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  // layout: 'vertical',
  schema: [
    {
      component: 'PersonalFavoriteSelect',
      fieldName: 'favoriteId',
      label: '人员收藏夹',
      componentProps: {
        allowClear: true,
      },
      // help: '',
      rules: 'selectRequired',
    },
  ],
  showDefaultActions: false,
});

const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
  {
    initializedGetter: defaultFormValueGetter(formApi),
    currentGetter: defaultFormValueGetter(formApi),
  },
);

interface AddToData {
  type: 'check' | 'search';
  records: EmployeeVO[];
  searchData?: Record<string, any>;
  total: number;
}

const [BasicModal, modalApi] = useVbenModal({
  fullscreenButton: false,
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      checkedCount.value = 0;
      return null;
    }
    modalApi.modalLoading(true);

    const { total } = modalApi.getData() as AddToData;
    checkedCount.value = total;
    markInitialized();

    modalApi.modalLoading(false);
  },
});

async function handleConfirm() {
  try {
    modalApi.lock(true);
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    const data = cloneDeep(await formApi.getValues()) as any;
    const { type, records, searchData } = modalApi.getData() as AddToData;
    if (type === 'check') {
      const addApi = props.addByCheckCompanyApi || personalFavoriteAddMember;
      const idsKey = props.addByCheckCompanyApi ? 'companyIds' : 'employeeIds';
      await addApi({
        [idsKey]: records.map((item) => item[props.idKey]),
        favoriteId: data.favoriteId,
      });
    }
    if (type === 'search') {
      await props.addBySearchApi({
        ...searchData,
        favoriteId: data.favoriteId,
      });
    }
    resetInitialized();
    emit('reload');
    modalApi.close();
  } catch (error) {
    console.error(error);
  } finally {
    modalApi.lock(false);
  }
}

async function handleClosed() {
  await formApi.resetForm();
  resetInitialized();
}
</script>

<template>
  <BasicModal
    title="加入人员收藏夹"
    class="w-[550px]"
    :confirm-text="confirmText"
  >
    <BasicForm />
  </BasicModal>
</template>
